<template>
  <div class="major-edit-container">
    <!-- 专业选择区域 -->
    <div class="major-selection-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>专业选择</span>
            <el-button type="primary" size="small" @click="showAddMajorDialog">
              新增专业
            </el-button>
          </div>
        </template>
        
        <div class="major-selector">
          <el-select 
            v-model="selectedMajorId" 
            placeholder="请选择专业"
            style="width: 300px;"
            filterable
            remote
            :remote-method="remoteMethod"
            :loading="majorsLoading"
            clearable
            @change="handleMajorChange"
          >
            <el-option
              v-for="major in majorsForSelect"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
          
          <el-button 
            type="primary" 
            @click="confirmMajorSelection"
            :disabled="!selectedMajorId"
            style="margin-left: 10px;"
          >
            确认
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 毕业要求编辑区域 -->
    <div class="graduation-requirements-section" v-if="selectedMajor">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>毕业要求编辑 - {{ selectedMajor.name }}</span>
            <el-button type="primary" @click="saveGraduationRequirements" style="margin-left: 10px;">保存</el-button>
          </div>
        </template>
        
        <!-- 年级选择 -->
        <div class="grade-selection">
          <el-input
            v-model="selectedGrade"
            placeholder="请输入入学学年（如：2024）"
            style="width: 200px;"
            @input="handleGradeChange"
          />
          <el-button 
            type="primary" 
            @click="loadGraduationRequirements"
            :disabled="!selectedGrade"
            style="margin-left: 10px;"
          >
            查询毕业要求
          </el-button>
        </div>

        <!-- 毕业要求内容 -->
        <div class="requirements-content" v-if="graduationRequirements.length > 0">
          <div class="requirements-header">
            <h3>{{ selectedGrade }}级毕业要求</h3>
            <el-button type="primary" @click="addRequirement">
              新增要求
            </el-button>
          </div>
          
          <div class="requirements-list">
            <el-card 
              v-for="(requirement, index) in graduationRequirements" 
              :key="requirement.id"
              class="requirement-card"
            >
              <template #header>
                <div class="requirement-header">
                  <div class="requirement-info">
                    <el-input
                      v-model="requirement.id"
                      placeholder="序号"
                      style="width: 80px;"
                      @input="sortRequirements"
                    />
                    <el-input
                      v-model="requirement.name"
                      placeholder="要求名称"
                      style="width: 200px; margin-left: 10px;"
                    />
                  </div>
                  <div class="requirement-actions">
                    <el-button 
                      type="success" 
                      size="small"
                      @click="addIndexPoint(requirement)"
                    >
                      添加指标点
                    </el-button>
                    <el-button 
                      type="danger" 
                      size="small"
                      @click="deleteRequirement(index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
              
              <div class="requirement-content">
                <el-input
                  v-model="requirement.desc"
                  type="textarea"
                  placeholder="请输入要求描述"
                  :rows="3"
                  style="margin-bottom: 15px;"
                />
                
                <!-- 指标点列表 -->
                <div class="index-points" v-if="requirement.indexPoints && requirement.indexPoints.length > 0">
                  <h4>指标点：</h4>
                  <div 
                    v-for="(point, pointIndex) in requirement.indexPoints" 
                    :key="point.index_id"
                    class="index-point-item"
                  >
                    <div class="index-point-header">
                      <span class="index-id">{{ point.index_id }}</span>
                      <el-button 
                        type="danger" 
                        size="small"
                        @click="deleteIndexPoint(requirement, pointIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                    <el-input
                      v-model="point.index_desc"
                      type="textarea"
                      placeholder="请输入指标点描述"
                      :rows="2"
                    />
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 无毕业要求时的提示 -->
        <div class="no-requirements" v-else-if="hasSearched">
          <el-empty description="该年级暂无毕业要求">
            <el-button type="primary" @click="addRequirement">
              新增毕业要求
            </el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 新增专业对话框 -->
    <el-dialog
      v-model="addMajorDialogVisible"
      title="新增专业"
      width="500px"
    >
      <el-form :model="newMajorForm" label-width="100px">
        <el-form-item label="专业名称">
          <el-input v-model="newMajorForm.name" placeholder="请输入专业名称" />
        </el-form-item>
        <el-form-item label="所属教研室">
          <el-input v-model="newMajorForm.office" placeholder="请输入所属教研室" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addMajorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddMajor">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { majorApi } from '@/api/majorApi.js'

// 模拟专业数据
const mockMajors = [
  { id: 1, name: '计算机科学与技术', office: '计算机学院' },
  { id: 2, name: '软件工程', office: '软件学院' },
  { id: 3, name: '人工智能', office: '人工智能学院' }
]

// 模拟毕业要求数据
const mockGraduationRequirements = [
  {
    id: 1,
    name: '工程知识',
    desc: '能够将数学、自然科学、工程基础和专业知识用于解决复杂工程问题。',
    indexPoints: [
      { index_id: '1.1', index_desc: '掌握数学、自然科学、工程基础和专业知识，能够将其应用于复杂工程问题的建模和分析。' },
      { index_id: '1.2', index_desc: '能够运用相关知识和工具，对复杂工程问题进行识别、表达和分析。' }
    ]
  },
  {
    id: 2,
    name: '问题分析',
    desc: '能够应用数学、自然科学和工程科学的基本原理，识别、表达、并通过文献研究分析复杂工程问题，以获得有效结论。',
    indexPoints: [
      { index_id: '2.1', index_desc: '能够识别和表达复杂工程问题的关键要素。' },
      { index_id: '2.2', index_desc: '能够通过文献研究分析复杂工程问题，获得有效结论。' }
    ]
  }
]

// 响应式数据
const majors = ref([...mockMajors])
const selectedMajorId = ref(null)
const selectedMajor = ref(null)
const selectedGrade = ref('')
const graduationRequirements = ref([])
const hasSearched = ref(false)
const addMajorDialogVisible = ref(false)
const newMajorForm = ref({ name: '', office: '' })

// 专业下拉数据
const majorsForSelect = ref([])
const majorsLoading = ref(false)

// 计算属性：选中的专业
const selectedMajorComputed = computed(() => {
  return majors.value.find(major => major.id === selectedMajorId.value)
})

// 专业选择变化
const handleMajorChange = (id) => {
  selectedMajor.value = majorsForSelect.value.find(m => m.id === id) || null
  // 清空毕业要求数据
  graduationRequirements.value = []
  hasSearched.value = false
}

// 确认专业选择
const confirmMajorSelection = () => {
  if (!selectedMajorId.value) {
    ElMessage.warning('请先选择专业')
    return
  }
  selectedMajor.value = majorsForSelect.value.find(m => m.id === selectedMajorId.value) || null
  if (!selectedMajor.value) {
    ElMessage.error('未找到专业信息')
    return
  }
  ElMessage.success(`已选择专业：${selectedMajor.value.name}`)
}

// 年级变化
const handleGradeChange = () => {
  // 清空毕业要求数据
  graduationRequirements.value = []
  hasSearched.value = false
}

// 查询毕业要求
const loadGraduationRequirements = async () => {
  if (!selectedGrade.value) {
    ElMessage.warning('请输入入学学年')
    return
  }
  if (!selectedMajorId.value) {
    ElMessage.warning('请先选择专业')
    return
  }
  try {
    const res = await majorApi.queryGraduationRequirement({ majorId: selectedMajorId.value, grade: selectedGrade.value })
    graduationRequirements.value = (res.data && res.data.graduation_requirement) ? res.data.graduation_requirement : []
    hasSearched.value = true
    ElMessage.success(`已加载${selectedGrade.value}级毕业要求`)
  } catch (e) {
    graduationRequirements.value = []
    hasSearched.value = true
    ElMessage.error('毕业要求查询失败')
  }
}

// 保存毕业要求
const saveGraduationRequirements = async () => {
  if (!selectedMajorId.value) {
    ElMessage.warning('请先选择专业')
    return
  }
  if (!selectedGrade.value) {
    ElMessage.warning('请输入入学学年')
    return
  }
  try {
    await majorApi.saveGraduationRequirement({
      majorId: selectedMajorId.value,
      grade: selectedGrade.value,
      graduation_requirement: graduationRequirements.value
    })
    ElMessage.success('成功保存')
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

// 显示新增专业对话框
const showAddMajorDialog = () => {
  newMajorForm.value = { name: '', office: '' }
  addMajorDialogVisible.value = true
}

// 确认新增专业
const confirmAddMajor = () => {
  if (!newMajorForm.value.name.trim()) {
    ElMessage.warning('请输入专业名称')
    return
  }
  
  if (!newMajorForm.value.office.trim()) {
    ElMessage.warning('请输入所属教研室')
    return
  }
  
  // 新增专业
  const newId = Math.max(...majors.value.map(m => m.id)) + 1
  const newMajor = {
    id: newId,
    name: newMajorForm.value.name,
    office: newMajorForm.value.office
  }
  
  majors.value.push(newMajor)
  addMajorDialogVisible.value = false
  ElMessage.success('新增专业成功')
}

// 新增毕业要求
const addRequirement = () => {
  const newId = graduationRequirements.value.length > 0 
    ? Math.max(...graduationRequirements.value.map(r => r.id)) + 1 
    : 1
  
  const newRequirement = {
    id: newId,
    name: '',
    desc: '',
    indexPoints: []
  }
  
  graduationRequirements.value.push(newRequirement)
}

// 删除毕业要求
const deleteRequirement = (index) => {
  graduationRequirements.value.splice(index, 1)
  ElMessage.success('删除成功')
}

// 添加指标点
const addIndexPoint = (requirement) => {
  const pointCount = requirement.indexPoints ? requirement.indexPoints.length : 0
  const newIndexId = `${requirement.id}.${pointCount + 1}`
  
  if (!requirement.indexPoints) {
    requirement.indexPoints = []
  }
  
  requirement.indexPoints.push({
    index_id: newIndexId,
    index_desc: ''
  })
}

// 删除指标点
const deleteIndexPoint = (requirement, pointIndex) => {
  requirement.indexPoints.splice(pointIndex, 1)
  
  // 重新排序指标点序号
  requirement.indexPoints.forEach((point, index) => {
    point.index_id = `${requirement.id}.${index + 1}`
  })
  
  ElMessage.success('删除指标点成功')
}

// 排序毕业要求
const sortRequirements = () => {
  graduationRequirements.value.sort((a, b) => a.id - b.id)
  
  // 重新排序指标点序号
  graduationRequirements.value.forEach(requirement => {
    if (requirement.indexPoints) {
      requirement.indexPoints.forEach((point, index) => {
        point.index_id = `${requirement.id}.${index + 1}`
      })
    }
  })
}

// 远程模糊查询专业
const remoteMethod = async (query) => {
  if (!query) {
    majorsForSelect.value = []
    return
  }
  majorsLoading.value = true
  try {
    const res = await majorApi.fuzzyQueryMajor(query)
    majorsForSelect.value = res.data || []
  } catch (e) {
    majorsForSelect.value = []
  } finally {
    majorsLoading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 从localStorage获取当前选中的专业ID（如果是从MajorList跳转过来的）
  const currentMajorId = localStorage.getItem('currentMajorId')
  if (currentMajorId) {
    selectedMajorId.value = parseInt(currentMajorId)
    selectedMajor.value = selectedMajorComputed.value
    localStorage.removeItem('currentMajorId') // 清除localStorage
  }
})
</script>

<style scoped>
.major-edit-container {
  padding: 20px;
}

.major-selection-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.major-selector {
  display: flex;
  align-items: center;
}

.graduation-requirements-section {
  margin-top: 20px;
}

.grade-selection {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.requirements-content {
  margin-top: 20px;
}

.requirements-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.requirements-header h3 {
  margin: 0;
  color: #409EFF;
}

.requirements-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.requirement-card {
  border: 1px solid #EBEEF5;
}

.requirement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.requirement-info {
  display: flex;
  align-items: center;
}

.requirement-actions {
  display: flex;
  gap: 10px;
}

.requirement-content {
  padding: 10px 0;
}

.index-points {
  margin-top: 15px;
}

.index-points h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.index-point-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #F0F0F0;
  border-radius: 4px;
  background-color: #FAFAFA;
}

.index-point-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.index-id {
  font-weight: bold;
  color: #409EFF;
  background-color: #ECF5FF;
  padding: 2px 8px;
  border-radius: 4px;
}

.no-requirements {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 